-- 日志管理器
-- Author: Colocasia
-- Date: 2019-07-16

local skynet = require "skynet"
require "skynet.manager"

local timer = require "timer"
local color = require 'color';
local string = require "us.string"

local priority_reg = "%[color%((%d)%)%]";
local text_color = {
	color.clear,
	color.blue,
	color.cyan,
	color.green,
	color.yellow,
	color.red,
	color.magenta,
};

local string_format = string.format;
local string_match = string.match;
local string_gsub = string.gsub;


local logfile
local cur_date

local function get_date()
	-- debug testing, create by second, we may create a new file every second
	-- return os.date("%Y-%m-%d-%M-%S", skynet.time())
	return os.date("%Y-%m-%d", os.time());
end

local function open_log_today()
	local date = get_date()
	local file_name = string_format("../log/skynet/%s.log", date)
	local fd = io.open(file_name, "a")
	assert(fd, string_format("open log failed, file_name = %s", file_name))
	print("[logcat] new file_name, fd = ", file_name, fd)
	return fd
end

skynet.register_protocol {
	name = "text",
	id = skynet.PTYPE_TEXT,
	unpack = skynet.tostring,
	dispatch = function(_, address, msg, ...)
		-- 输出终端
		local priority = string_match(msg or "", priority_reg) or 1;
		local msg = string_gsub(msg, priority_reg, "");
		local content = string_format("[%s][%s] %s", skynet.address(address), os.date("%m/%d/%y %H:%M:%S", os.time()), msg or "")
		print(string_format("%s%s %s ", text_color[tonumber(priority)], content, color.reset));
		-- 输出日志
		logfile = logfile or open_log_today();
		logfile:write(content.."\n")
		logfile:flush()
	end
}

skynet.start(function()
	print('--start logcat ---')

	cur_date = get_date()
	logfile = logfile or open_log_today();

	local function check_date()
		local date = get_date()
		if date ~= cur_date then
			cur_date = date
			print("[logcat] day passed, open a new log file.")
			logfile:close()
			logfile = open_log_today()
		end
	end
	timer.add_timer("logcat_check", 60, true, check_date);

	skynet.register ".logger"
	print('--- logcat start fin ---')
end)

